package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.MessageUtil;
import com.ruoyi.common.utils.weixin.po.AccessToken;
import com.ruoyi.common.utils.weixin.po.AccessUser;
import com.ruoyi.common.utils.weixin.po.TextMessage;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.weixin.WeixinUtil;
import com.ruoyi.system.service.IWeixinService;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信 业务层处理
 * 
 * @author admin
 */
@Service
public class WeixinServiceImpl implements IWeixinService{

	private static final Logger LOGGER = LoggerFactory.getLogger(WeixinServiceImpl.class);
	
	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private WxCodeMapper wxCodeMapper;
	@Autowired
	private WxUserMapper wxUserMapper;
	@Autowired
	private WxSendMsgModelMapper wxSendMsgModelMapper;
	@Autowired
	private WxSendMsgLogMapper wxSendMsgLogMapper;
    @Autowired
    private WxErrCompareMapper wxErrCompareMapper;
	@Autowired
	private WxGroupSendingScheduleMapper sendingScheduleMapper;


	/**
	 * 根据条件分页查询微信号数据
	 * 
	 * @return 微信号数据集合信息
	 */
	@Override
	@DataScope(tableAlias = "u")
	public List<WxCode> selectWxCodeList(WxCode wxCode) {
		return wxCodeMapper.selectWxCodeList(wxCode);
	}
	
	@Override
	public List<WxCode> selectWxCodes() {
		return wxCodeMapper.selectWxCodes();
	}
	
	/**
	 * 根据条件分页查询微信user数据
	 * 
	 * @return 微信user数据集合信息
	 */
	@Override
	@DataScope(tableAlias = "u")
	public List<WxUser> selectWxUserList(WxUser wxUser) {
		return wxUserMapper.selectWxUserList(wxUser);
	}
	
	@Override
	public List<WxUser> selectWxUserByCodeId(String codeId) {
		WxUser user = new WxUser();
		user.setWxCode(codeId);
		return  wxUserMapper.selectWxUserByCodeId(user);
	}


	@Override
	@DataScope(tableAlias = "u")
	public List<WxSendMsgLog> selectWxSendMsgLogList(WxSendMsgLog wxSendMsgLog){
		return wxSendMsgLogMapper.selectWxSendMsgLogList(wxSendMsgLog);
	}

	@Override
	public List<WxSendMsgModel> selectWxSendMsgModelList(WxSendMsgModel wxSendMsgModel) {
		return wxSendMsgModelMapper.selectWxSendMsgModelList(wxSendMsgModel);
	}

	@Override
	@DataScope(tableAlias = "u")
	public List<WxGroupSendingSchedule> selectWxGroupSendingScheduleList(WxGroupSendingSchedule sendingSchedule){
		return sendingScheduleMapper.selectWxGroupSendingScheduleList(sendingSchedule);
	}
	@Override
	public List<WxGroupSendingSchedule> selectSendingScheduleDatas(String methodName){
		WxGroupSendingSchedule sendingSchedule = new WxGroupSendingSchedule();
		sendingSchedule.setMethodName(methodName);
		return sendingScheduleMapper.selectSendingScheduleDatas(sendingSchedule);

	}

	@Override
	public List<WxSendMsgModel> selectWxSendMsgModels() {
		return wxSendMsgModelMapper.selectWxSendMsgModels();
	}

	@Override
	public WxCode getEntityByAppId(String appId) {
		WxCode wxCode = new WxCode();
		wxCode.setAppId(appId);
		return wxCodeMapper.getEntity(wxCode);
	}

	@Override
	public WxCode getEntityById(Long id) {
		WxCode wxCode = new WxCode();
		wxCode.setWxId(id);
		return wxCodeMapper.getEntity(wxCode);
	}
	
	@Override
	public WxCode getEntityByWxCode(String wxCode) {
		WxCode code = new WxCode();
		code.setWxCode(wxCode);
		return wxCodeMapper.getEntity(code);
	}
	@Override
	public WxGroupSendingSchedule getSendingScheduleById(Long id){
		WxGroupSendingSchedule sendingSchedule = new WxGroupSendingSchedule();
		sendingSchedule.setId(id);
		return sendingScheduleMapper.getEntity(sendingSchedule);
	}

    @Override
    public WxErrCompare selectWxErrCompareByErrCode(String errCode){
        WxErrCompare wxErrCompare = new WxErrCompare();
        wxErrCompare.setErrCode(errCode);
        return wxErrCompareMapper.selectWxErrCompareByErrCode(wxErrCompare);
    }


	/**
	 * 校验微信号名称是否唯一
	 * 
	 * @param wxCode
	 * @return
	 */
	@Override
	public String checkWxCodeUnique(WxCode wxCode) {
		if(StringUtils.isNotEmpty(wxCode.getWxCode())) {
			WxCode code_ = wxCodeMapper.checkWxCodeUnique(wxCode);
			if (StringUtils.isNotNull(code_)) 
				return UserConstants.WX_CODE_NOT_UNIQUE;
		}
		return UserConstants.WX_CODE_UNIQUE;
	}
	
	/**
	 * 校验微信号名称是否唯一
	 * 
	 * @param wxUser
	 * @return
	 */
	@Override
	public String checkOpenIdUnique(WxUser wxUser) {
		if(StringUtils.isNotEmpty(wxUser.getOpenid())) {
			WxUser user_ = wxUserMapper.checkOpenIdUnique(wxUser);
			if (StringUtils.isNotNull(user_)) 
				return UserConstants.WX_CODE_NOT_UNIQUE;
		}
		return UserConstants.WX_CODE_UNIQUE;
	}


	/**
	 * 修改保存微信号信息
	 *
	 * @param wxCode
	 * @return 结果
	 */
	@Override
	public int updateWxCode(WxCode wxCode){
		return wxCodeMapper.updateWxCode(wxCode);
	}

	@Override
	public WxSendMsgModel getwxTemplateById(Long modelId){
		WxSendMsgModel wxSendMsgModel = new  WxSendMsgModel();
		wxSendMsgModel.setId(modelId);
		return wxSendMsgModelMapper.getEntity(wxSendMsgModel);
	}

	@Override
	public int insertWxCode(WxCode wxCode) {
		return wxCodeMapper.insertWxCode(wxCode);
	}
	
	@Override
	public int insertWxUser(WxUser wxUser) {
		/* 判断是否已存在 */
		if(StringUtils.isNotEmpty(wxUser.getOpenid())) {
			if(checkOpenIdUnique(wxUser).equals(UserConstants.WX_CODE_UNIQUE)) // 未查到
				return wxUserMapper.insertWxUser(wxUser);
			else return wxUserMapper.updateWxUser(wxUser); // 更新用户
		}
		return Integer.valueOf(UserConstants.EXCEPTION); // 异常状态
	}

	@Override
	public int insertWxSendMsgModel(WxSendMsgModel wxSendMsgModel) {
		return wxSendMsgModelMapper.insertWxSendMsgModel(wxSendMsgModel);
	}

	@Override
	public int insertSendingSchedule(WxGroupSendingSchedule sendingSchedule){
		return sendingScheduleMapper.insertSendingSchedule(sendingSchedule);
	}

	@Override
	public int updateSendingSchedule(WxGroupSendingSchedule sendingSchedule){
		return sendingScheduleMapper.updateSendingSchedule(sendingSchedule);
	}

	/**
	 * 修改保存微信模板信息
	 *
	 * @param wxSendMsgModel
	 * @return 结果
	 */
	@Override
	public int updateWxSendMsgModel(WxSendMsgModel wxSendMsgModel){
		return wxSendMsgModelMapper.updateWxSendMsgModel(wxSendMsgModel);
	}

	@Override
	public int deleteWxCodeByIds(String ids) throws Exception {
		Long[] codeIds = Convert.toLongArray(ids);
		return wxCodeMapper.deleteWxCodeByIds(codeIds);
	}

	@Override
	public int deleteWxSendMsgModelByIds(String ids) throws Exception {
		Long[] modelIds = Convert.toLongArray(ids);
		return wxSendMsgModelMapper.deleteWxSendMsgModelByIds(modelIds);
	}

	@Override
	public int deleteWxSendMsgLogByIds(String ids) throws Exception {
		Long[] codeIds = Convert.toLongArray(ids);
		return wxSendMsgLogMapper.deleteWxSendMsgLogByIds(codeIds);
	}

	@Override
	public int deleteSengdingSchduleByIds(String ids) throws Exception {
		Long[] ids_ = Convert.toLongArray(ids);
		return sendingScheduleMapper.deleteSengdingSchduleByIds(ids_);
	}
	
	
	@Override
	public WxUser getWxUserByAccessUser(String ACCESS_TOKEN, String OPENID) throws Exception {
		WxUser wxUser = new WxUser();
		JSONObject object = WeixinUtil.getAccessUser(ACCESS_TOKEN, OPENID);
		if(object != null) {
			wxUser.setOpenid(object.getString("openid"));
			wxUser.setNickName(object.getString("nickname"));
			wxUser.setSex(object.getInteger("sex"));
			wxUser.setLanguage(object.getString("language"));
			wxUser.setCity(object.getString("city"));
			wxUser.setProvince(object.getString("province"));
			wxUser.setCountry(object.getString("country"));
			wxUser.setHeadImgUrl(object.getString("headimgurl"));
			Long subscribe_time = object.getLongValue("subscribe_time")*1000;
			wxUser.setSubscribeTime(simpleDateFormat.parse(DateUtils.stampToDate(subscribe_time)));
		}
		return wxUser;
	}

	@Override
	public int insertWxSendMsgLog(WxCode wxCode,String accessToken,int successNum,int errorNum,String remark){
		WxSendMsgLog sendLog = new WxSendMsgLog();
		sendLog.setWxCode(wxCode.getWxCode());
		sendLog.setWxName(wxCode.getWxName());
		sendLog.setAccessToken(accessToken);
		sendLog.setSuccessNum(successNum);
		sendLog.setErrorNum(errorNum);
		sendLog.setSendTime(new Date());
		sendLog.setRemark(remark);
		return wxSendMsgLogMapper.insertWxSendMsgLog(sendLog);
	}

	/* 群发短信 */
	@Override
	public int groupSending(int type,String wxCode,String jsonStr,String remark){
		int errorNum = 0;
		int successNum = 0;
		/* 根据 wxCode 获取 WxCode  wxb9d9e668dda34ab6*/
		WxCode code = this.getEntityByWxCode(wxCode);
		if(code != null) {

			if(StringUtils.isNotEmpty(code.getAccessToken())) {
				// 根据接口获取所有的关注用户
				List<AccessUser> users = WeixinUtil.getAccessUsers(code.getAccessToken());
				// 根据 wxCode 获取 关注的用户数据
				//List<WxUser> wx_users = weixinService.selectWxUserByCodeId(wxCode);
				if(users.size() > 0) {
					for(AccessUser user : users) {
					int No = users.size();
							String jsonMsg = WeixinUtil.JsonTokfMsg(type,jsonStr, user.getOpenid());
							// 发送客服消息
							int errorCode = WeixinUtil.sendCustomMessage(code.getAccessToken(), jsonMsg);

							// 返回消息发送成功
							if (errorCode == 0) successNum++;
							else errorNum++;

							if (errorCode == 40003 || errorCode == 42001 || errorCode == 40001)  // 返回 40003 代码直接失败（token 对应不上）
								return Constants.TOAJAX_FAIL;
							//LOGGER.info("=>> 已成功推送 ：" + successNum + " 条, ==>> 失败 : "+ errorNum +" 条, 还需要发送 "+ No-- + "条数据。 总发送 "+ users.size() );
					}
					// 插入消息发送日志

					this.insertWxSendMsgLog(code,code.getAccessToken(),successNum,errorNum,"消息发送成功("+remark+")");
					return Constants.TOAJAX_SUCCESS;
				}
			}
			// 插入消息发送日志
			this.insertWxSendMsgLog(code,code.getAccessToken(),successNum,1,"无效的 accessToken 信息("+remark+")");
		}
		// 返回消息发送失败
		return Constants.TOAJAX_FAIL;

	}


	@Override
	public String ObjectToJson(WxSendMsgModel sendMsgModel) {
		String jsonStr = "";
		if(sendMsgModel != null){
			jsonStr = "{'topName':'"+sendMsgModel.getTopName()+"',";
			jsonStr += "'productOneName':'"+sendMsgModel.getProductOneName()+"',";
			jsonStr += "'productOneLink':'"+sendMsgModel.getProductOneLink()+"',";
			jsonStr += "'productOneLinkText':'"+sendMsgModel.getProductOneLinkText()+"',";
			jsonStr += "'productTwoName':'"+sendMsgModel.getProductTwoName()+"',";
			jsonStr += "'productTwoLink':'"+sendMsgModel.getProductTwoLink()+"',";
			jsonStr += "'productTwoLinkText':'"+sendMsgModel.getProductTwoLinkText()+"',";
			jsonStr += "'endName':'"+sendMsgModel.getEndName()+"'}";
		}
		return jsonStr;
	}

	@Override
	public String newMessageRequest(HttpServletRequest request, WxCode code) {
		String respMessage = null;
		try {
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息内容
			String content = requestMap.get("Content");


			// 文本消息 (自动回复消息设置)
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				//这里根据关键字执行相应的逻辑
                /*if(content.equals("xxx")){

                }*/
				/*TextMessage text = new TextMessage();
				text.setContent("霍霍哈嘿"+content);
				text.setToUserName(fromUserName);
				text.setFromUserName(toUserName);
				text.setCreateTime(new Date().toString());
				text.setMsgType(msgType);
				respMessage = MessageUtil.textMessageToXml(text);*/
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				String eventType = requestMap.get("Event");// 事件类型
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					//文本消息
					TextMessage text = new TextMessage();
					text.setContent("优质口子通道，回复任意数字，即可申请！");
					text.setToUserName(fromUserName);
					text.setFromUserName(toUserName);
					text.setCreateTime(new Date().toString());
					text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
					respMessage = MessageUtil.textMessageToXml(text);

					// 发送客服消息
					AccessToken token = WeixinUtil.getAccessToken(code.getAppId(),code.getAppSecret());
					LOGGER.debug(" token :" + token.getToken());

					String returnMsg = "{ \"touser\" : " + " \""+ fromUserName +"\" " + ","+
						" \"msgtype\" : " + " \"text\" ," +
						" \"text\" :{ " +
							" \"content\" : " + " \" 欢迎关注小贝口袋！\n\r" +
							" 请输入您的内部通道验证码，领取您的额度！\r\r" +
							"【新用户极速通道】\r" + "      12月最新产品汇总: <a href='http://news.wihens.com/#/?channel_id=169'>点击申请</a>\r" +
							"【强力推荐】\r" + "      <a href='https://12i.cn/00QSfc'>点击申请下款率较高的产品</a>\r" +
							"  温馨提醒：同时申请五个产品以上会提高通过率，以便满足您的需求！\" }" +
						"}";
					// 发送客服消息
					int errorCode = WeixinUtil.sendCustomMessage(token.getToken(), returnMsg);
					LOGGER.debug(" errorCode :" + errorCode);

				}
				// 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					LOGGER.info("已取消订阅");
				}
			}
		}
		catch (Exception e) {
			LOGGER.error("error......");
		}
		return respMessage;
	}


}
